package im.starchat.chat.adapter;


import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.tencent.TIMElemType;
import com.tencent.TIMMessage;
import com.tencent.TIMTextElem;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.dialog.MemberDialogFragment;
import im.starchat.chat.rest.model.ChatEntity;
import im.starchat.chat.rest.model.CommentBean;
import im.starchat.chat.rest.model.MemberInfo;
import im.starchat.chat.utils.Constants;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.UserUtils;


public class ChatMsgListAdapter extends BaseAdapter {

    private static String TAG = ChatMsgListAdapter.class.getSimpleName();
    private static final int ITEMCOUNT = 9;
    private List<ChatEntity> listMessage = null;
    private List<CommentBean> comments;
    private LayoutInflater inflater;
    private LinearLayout layout;
    public static final int TYPE_TEXT_SEND = 0;
    public static final int TYPE_TEXT_RECV = 1;
    private Context context;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private ArrayList<MemberInfo> mMemberList;
    //	private UserInfo myselfInfo;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private ViewHolder holder;
    private MemberInfo host;
    private XLApplication mQavsdkApplication;
    private String selfInRoom = "轻轻地" + UserUtils.getUserInstance().getNickname() + "来了";

    private ChatMsgListAdapter(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs().build();
        ImageLoader.getInstance().init(config);
    }

    public static ChatMsgListAdapter createInstanceFromMemList(Context context, List<ChatEntity> objects,
                                                               ArrayList<MemberInfo> memberList, MemberInfo hostMember, MemberListCallBack memberListCallBack) {
        ChatMsgListAdapter adapter = new ChatMsgListAdapter(context);
        adapter.context = context;
        adapter.inflater = LayoutInflater.from(context);
        adapter.listMessage = objects;
        adapter.mMemberList = memberList;
//		myselfInfo = myself;
        adapter.host = hostMember;
        adapter.mMemberListCallBack = memberListCallBack;
        return adapter;
    }

    public static ChatMsgListAdapter createInstanceFromComment(Context context, List<CommentBean> comments,
                                                               ArrayList<MemberInfo> memberList, MemberInfo hostMember, MemberListCallBack memberListCallBack) {
        ChatMsgListAdapter adapter = new ChatMsgListAdapter(context);
        adapter.context = context;
        adapter.inflater = LayoutInflater.from(context);
        adapter.comments = comments;
        adapter.mMemberList = memberList;
//		myselfInfo = myself;
        adapter.host = hostMember;
        adapter.mMemberListCallBack = memberListCallBack;
        return adapter;
    }

    public void refreshHost(MemberInfo hostMember) {
        host = hostMember;
    }

    public void refresCommentList(List<CommentBean> comments) {
        this.comments = comments;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return listMessage != null ? listMessage.size() : comments.size();
    }

    @Override
    public Object getItem(int position) {
        return listMessage != null ? listMessage.get(position) : comments.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        if (listMessage != null) {
            ChatEntity entity = listMessage.get(position);
            if (entity.getElem() != null) {
                if (entity.getElem().getType() == TIMElemType.Text) {
                    return entity.getIsSelf() ? TYPE_TEXT_SEND : TYPE_TEXT_RECV;
                }
            } else {
                return TYPE_TEXT_SEND;
            }
        }
        if (comments != null) {
            return TYPE_TEXT_RECV;
        }
        return -1;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (listMessage != null) {
            //直播
            return getViewOfListMessage(position, convertView, parent);
        } else {
            //回放
            return getViewOfComments(position, convertView, parent);
        }
    }

    public View getViewOfComments(final int position, View convertView, ViewGroup parent) {
        CommentBean entity = comments.get(position);
//		TIMTextElem elem = (TIMTextElem) entity.getElem();

//		Log.d(TAG, "ChatMsgListAdapter senderName " + entity.getSenderName());


        if (convertView == null) {
            convertView = (LinearLayout) inflater.inflate(R.layout.item_chat, null);
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.chat_content);
//			holder.mName = (TextView) convertView.findViewById(R.id.tv_name);
//			holder.icon = (CircularImageButton) convertView.findViewById(R.id.tv_chat_head_image);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        convertView.setVisibility(View.VISIBLE);

        mQavsdkApplication = (XLApplication) context.getApplicationContext();
//		host = mQavsdkApplication.getHostInfo();
        boolean hasUser = false;
        String identity = String.valueOf(entity.getId());
        String name = "";
        String content = "";

        if (identity.equals(PreferencesStorageUtil.getUserId(context))) {
            content = entity.getMessage();
            name = UserUtils.getUserInstance().getNickname() + ":";
            hasUser = true;

        } else {

            for (int i = 0; i < comments.size(); ++i) {
                String IDPhone = comments.get(i).getId() + "";
                if (IDPhone.equals(identity)) {

                    name = comments.get(i).getUser().getNickname() + ":";
                    hasUser = true;
                }
            }
//			for (int i = 0; i < mMemberList.size(); ++i) {
//				String IDPhone = mMemberList.get(i).getUserPhone();
//				if (IDPhone.equals(identity)) {
//
//					name = mMemberList.get(i).getUserName() + ":";
//					hasUser = true;
//				}
//			}
            if (host != null) {
                if (host.getUserPhone().equals(identity)) {
                    name = host.getUserName() + ":";
                    hasUser = true;
                }
            }
            content = entity.getMessage();
//			holder.mName.setText(identity + ":");
//			holder.text.setText(entity.getMessage());

        }
//		convertView.setVisibility(View.VISIBLE);
        if (!hasUser) {
            convertView.setVisibility(View.GONE);
        } else {
            SpannableStringBuilder builder = new SpannableStringBuilder(name + content);
            ForegroundColorSpan yellowSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.color_text_5));
            ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);
            builder.setSpan(yellowSpan, 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(whiteSpan, name.length(), name.length() + content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.text.setText(builder);
        }
        holder.text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMemberListCallBack != null) {
                    mMemberListCallBack.onCommentClick(comments.get(position));
                }
            }
        });
        System.out.println("name-->" + name + "content--->" + content);
        return convertView;
    }


    public View getViewOfListMessage(final int position, View convertView, ViewGroup parent) {
        ChatEntity entity = listMessage.get(position);
        TIMTextElem elem = (TIMTextElem) entity.getElem();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_chat, null);
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.chat_content);
//			holder.mName = (TextView) convertView.findViewById(R.id.tv_name);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        convertView.setVisibility(View.VISIBLE);

        mQavsdkApplication = (XLApplication) context.getApplicationContext();
        final String identity = entity.getSenderName();//用户的id
//		boolean hasUser = false;
        String name = "";
        String content = "";
//		if (identity.equals(PreferencesStorageUtil.getUserId(context))) {
//			content = elem.getText().toString();
//			name = UserUtils.getUserInstance().getNickname() + ":";
//			hasUser = true;
//		} else {
//			for (int i = 0; i < mMemberList.size(); ++i) {
//				String IDPhone = mMemberList.get(i).getUserPhone();
////				if (!mMemberList.get(i).getUserPhone().startsWith("86-
////				Toast.makeText(context, "IDPhone-->" + IDPhone, Toast.LENGTH_SHORT).show();
//				if (IDPhone.equals(entity.getSenderName())) {
//					name = mMemberList.get(i).getUserName() + ":";
//					hasUser = true;
//				}
//			}
//			content = elem.getText().toString();
////			holder.text.setText(elem.getText().toString());
//		}
//		if(!hasUser){
//			convertView.setVisibility(View.GONE);
//		}else{
//		if (identity.equals(PreferencesStorageUtil.getUserId(context))) {
//			content = elem.getText().toString();
//			name = UserUtils.getUserInstance().getNickname() + ":";
        String item;
        ForegroundColorSpan yellowSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.color_text_5));
        ForegroundColorSpan redSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.color_FA2E61));
        ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);
        if (Constants.MESSAGETYPE.GIFTMESSAGE.equals(entity.getMsgType())) {
            name = entity.getName() + ":";
            content = entity.getMsg();
            item = name + content;
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(content)) {
                SpannableStringBuilder builder = new SpannableStringBuilder(item);
                builder.setSpan(yellowSpan, 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                builder.setSpan(redSpan, name.length(), name.length() + content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.text.setText(builder);
            }
        } else {
            if (host != null && host.getUserPhone().equals(identity)) {
                name = host.getUserName() + ":";
                content = elem.getText().toString();
            } else {
                name = entity.getName() + ":";
                content = elem.getText().toString();
            }
            item = name + content;
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(content)) {
                SpannableStringBuilder builder = new SpannableStringBuilder(item);
                builder.setSpan(yellowSpan, 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                builder.setSpan(whiteSpan, name.length(), name.length() + content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                holder.text.setText(builder);
            }
        }

        holder.text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMemberListCallBack != null) {
                    mMemberListCallBack.onUserInfoClick(identity);
                }
            }
        });
        return convertView;
    }

    static class ViewHolder {
        public TextView text;
//		public TextView mName;
//		public CircularImageButton icon;
    }

    private MemberListCallBack mMemberListCallBack;

    public static interface MemberListCallBack {
        public void onCommentClick(CommentBean commentBean);
        public void onUserInfoClick(String userId);
    }

}